import request from '@/utils/request'

export default {
  name: 'pubMysqlCreate',
  data() {
    return {
      // card1
      cloudPlatformList: [],
      instanceChargeTypeList: [
        {"type": "POSTPAID", "name": "按量付费", "description": "先使用后付费，按需开通"},
        {"type": "PREPAID", "name": "包年包月", "description": "先付费后使用价格优惠"}
      ],
      vpcList: [],
      switchList: [],
      regionList: [],
      zoneList: [],
      instanceTypeList: [],
      sysDiskTypeList: [],
      securityGroupList: [],
      baseForm: {
        instanceChargeType: 'POSTPAID',
        cloudPlatformId: '',
        location: '',
        regionName: '',
        regionId: '',
        zoneId: '',
        vpcId: '',
        switchId: '',
        instanceFamilyId: '',
        instanceType: '',
        cpuCoreCount: null,
        memorySize: null,
        securityGroups: [],
        instanceName: '',
        description: '',
        version: '',
        port: 3306
      },
      loading: {
        regionId: false,
        zoneId: false,
        vpcId: false,
        switchId: false,
        instanceFamilyId: false,
        instanceType: false,
        sysDiskType: false,
        version: false
      },
      // card2
      vCPUList: [{"value": 1, "label": "1 vCPU"}, {"value": 2, "label": "2 vCPU"}, {"value": 4, "label": "4 vCPU"}, {"value": 8, "label": "8 vCPU"}, {"value": 16, "label": "16 vCPU"}, {"value": 32, "label": "32 vCPU"}],
      memoryList: [{"value": 1, "label": "1 GiB"}, {"value": 2, "label": "2 GiB"}, {"value": 4, "label": "4 GiB"}, {"value": 8, "label": "8 GiB"}, {"value": 16, "label": "16 GiB"}, {"value": 32, "label": "32 GiB"}],
      // 实例
      instanceList: [],
      pagination: {
        currentPage: 1,
        size: 5,
        total: 0
      },
      activeSpecTab: '1',
      specParamDialogVisible: false,
      specParamList: [],
      isIndeterminate: true,
      checkAllSpecParams: false,
      checkedSpecParamsTemp: [], // 选择展示的参数
      checkedSpecParams: [], // 确认选择展示的参数
      specParamsTableColumnVisible: {

      },
      updateSelect: true,

      // 镜像
      activeMirrorTab: '1',
      commonMirrorList: [],
      commonMirrorVersionList: [],
      instanceForm: {
        vCPUId: '',
        memoryId: '',
        specificationName: '',
        selectedInstanceId: '', // 所选表格中实例
        commonMirrorId: '',
        commonMirrorVersionId: ''
      },

      // card3
      diskTypeList: [],
      diskForm: {
        systemDiskList: [
          { type: null, capacity: null, quantity: null, iops: '-', performance: '-', release: true }
        ],
      },
      // card4 带宽和安全组
      bandwidthForm: {
        billingMode: 'fixed',
        group: '0',
        securityGroupName: '',
        securityGroupType: 'normal',
        IPv4Ports: []
      },
      IPv4PortList: [],

      // card 5 高级选项
      advancedOptionForm: {
        instanceName: '',
        description: '',
      },
      advancedOptionFormRules: {
        instanceName: [
          // { required: true, message: '请输入实例名称', trigger: 'blur' },
          { min: 2, max: 128, message: '实例名称长度为2-128个字符', trigger: 'blur' },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]/,
            message: '实例名称需以字母或中文开头',
            trigger: 'blur'
          }
        ],
        description: [
          { min: 2, max: 256, message: '描述长度为2-256个字符', trigger: 'blur' },
          {
            pattern: /^(?!https?:\/\/|https:\/\/)[\s\S]+$/,
            message: '描述不能以http://或https://开头',
            trigger: 'blur'
          }
        ]
      },
      // card right
      payForm: {
        instanceNum: 1,
        duration: ' ',
        autoRenew: false
      },
      maxInstanceNum: 1, // 最大购买实例数
      durationList: [],
      trueBool: true,
      price: {
        tradePrice: '',
        bandwidthPrice: ''
      },
      selectedRows: [],
      versionList: []
    }
  },
  created() {
  },
  computed: {
    selectedRegion() {
      return this.baseForm.regionName ? this.baseForm.regionName : ''
    },
    selectedZone() {
      const option = this.zoneList.find(i => i.zoneId === this.baseForm.zoneId)
      return option ? option.localName : ''
    },
    selectedVersion() {
      const option = this.versionList.find(i => i === this.baseForm.version)
      return option ? option : ''
    },
    selectedVpc() {
      const option = this.vpcList.find(i => i.vpcId === this.baseForm.vpcId)
      return option ? option.vpcName : ''
    },
    selectedSwitch() {
      const optionSwitch = this.switchList.find(i => i.vSwitchId === this.baseForm.switchId)
      return optionSwitch ? optionSwitch.vSwitchName : ''
    },
    selectedInstanceType() {
      if (this.baseForm.instanceType) {
        const option = this.instanceTypeList.find(i => i.typeId === this.baseForm.instanceType)
        return option ? option.typeId : ''
      }
      return ''
    },
    selectedSystemDisk() {
      if (this.diskForm.systemDiskList[0]) {
        const type = this.diskForm.systemDiskList[0].type
        const capacity = this.diskForm.systemDiskList[0].capacity
        return type && capacity ? capacity + " GB" : ''
      }
      return ''
    },
    //selectedSecurityGroup() {
    //  const option = this.baseForm.securityGroups.map(s => s.securityGroupName)
    //  return option ? option.join(',') : ''
    //},
    // 确认按钮
    createInstanceDisabled() {
      //  && this.selectedSecurityGroup
      return !(this.selectedRegion && this.selectedZone
        && this.selectedVpc && this.selectedSwitch
        && this.selectedInstanceType && this.selectedSystemDisk && this.selectedVersion)
    }
  },
  // 监听计算价格
  watch: {
    //baseForm: {
    //  deep: true,
    //  handler: function (newValue, oldValue) {
    //    this.instancePrice();
    //  }
    //},
    //diskForm: {
    //  deep: true,
    //  handler: function (newValue, oldValue) {
    //    this.instancePrice();
    //  }
    //},
  },
  async mounted() {
    await this.getCloudPlatformList()
  },
  methods: {
    // 云商列表
    getCloudPlatformList() {
      request({
        url: '/cloud/pub/v1.0/cloud_platform',
        method: 'get',
        params: {
          pageNo: 1,
          pageSize: 100
        }
      }).then(({data}) => {
        this.cloudPlatformList = data.pageData
        if (this.cloudPlatformList.length > 0) {
          this.baseForm.cloudPlatformId = this.cloudPlatformList[0].id
          this.changeCloudPlatform()
          // change other
          // this.getRegionList();
          this.getDurationList()
        }
      })
    },
    // 切换云平台时
    changeCloudPlatform() {
      this.baseForm.regionId = this.cloudPlatformList.filter(c => c.id == this.baseForm.cloudPlatformId)[0].regionId
      this.baseForm.regionName = this.cloudPlatformList.filter(c => c.id == this.baseForm.cloudPlatformId)[0].regionName
      this.baseForm.zoneId = ''
      this.baseForm.vpcId = ''
      this.baseForm.switchId = ''
      this.baseForm.instanceFamilyId = ''
      this.baseForm.instanceType = ''
      this.baseForm.version = ''
      this.regionList = []
      this.zoneList = []
      this.vpcList = []
      this.switchList = []
      this.instanceTypeList = []
      // this.getRegionList()
      // 包年包月时间
      this.getDurationList()

      this.baseForm.version = ''
      this.instanceFamilyList = []
      // 清空磁盘类型
      this.dataDiskTypeList = []
      this.sysDiskTypeList = []
      // 清空磁盘内容
      this.diskForm.dataDiskList = []
      this.diskForm.systemDiskList[0] = { type: null, capacity: null, quantity: null, iops: '-', performance: '-', release: true }
      //
      this.getZoneList()
      this.getInstanceTypeList()
      // this.getImagePlatform()
      this.getSecurityGroupList()
      this.getVersion()
    },
    //  切换大区时
    changeRegion() {
      this.baseForm.zoneId = ''
      this.baseForm.vpcId = ''
      this.baseForm.switchId = ''
      this.baseForm.instanceFamilyId = ''
      this.baseForm.instanceType = ''
      this.zoneList = []
      this.vpcList = []
      this.switchList = []
      this.instanceTypeList = []
      // 清空磁盘类型
      this.sysDiskTypeList = []
      // 清空磁盘内容
      this.diskForm.systemDiskList[0] = { type: null, capacity: null, quantity: null, iops: '-', performance: '-', release: true }
      this.baseForm.version = ''
      this.getVersion()
      this.getSecurityGroupList()
    },
    changeVersion() {
      this.getZoneList()
    },
    changeZoneList() {
      this.baseForm.vpcId = ''
      this.baseForm.switchId = ''
      this.baseForm.instanceFamilyId = ''
      this.baseForm.instanceType = ''
      this.vpcList = []
      this.switchList = []
      this.instanceTypeList = []
      // 清空磁盘类型
      this.sysDiskTypeList = []
      // 清空磁盘内容
      this.diskForm.systemDiskList[0] = { type: null, capacity: null, quantity: null, iops: '-', performance: '-', release: true }
      //
      this.getVpcList()
      this.getDiskData()
    },
    // 切换网络
    changeVpcList() {
      this.baseForm.switchId = ''
      this.switchList = []
      this.getSwitchList()
    },
    // 获取大区
    // getRegionList() {
    //   let _self = this
    //   _self.loading.regionId = true
    //   request({
    //     url: '/cloud/pub/v1.0/mysql/regions_zones/region?dataCenterId=' + this.baseForm.cloudPlatformId,
    //     method: 'get'
    //   }).then(data => {
    //     _self.loading.regionId = false
    //     this.regionList = data.data
    //     if (this.regionList.length > 0) {
    //       this.baseForm.regionId = this.regionList[0].regionId
    //       this.changeRegion()
    //     }
    //   }).catch(error => {
    //     _self.loading.regionId = false
    //   })
    // },
    // 包年包月时间
    getDurationList() {
      let _self = this
      request({
        url: '/cloud/pub/v1.0/duration_available?dataCenterId=' + this.baseForm.cloudPlatformId,
        method: 'get'
      }).then(data => {
        _self.durationList = data.data
        if (_self.durationList.length > 0) {
          _self.payForm.duration = this.durationList[0].id
        }
      }).catch(error => {
        console.error(error)
      })
    },
    // 获取可用区
    getZoneList() {
      let _self = this
      _self.loading.zoneId = true
      request({
        url: '/cloud/pub/v1.0/mysql/regions_zones/zone',
        params: {
          dataCenterId: this.baseForm.cloudPlatformId,
          regionUuid: this.baseForm.regionId,
          engineVersion: this.baseForm.version,
          category: 'Basic'
        },
        method: 'get'
      }).then(data => {
        _self.loading.zoneId = false
        this.zoneList = data.data
        if (this.zoneList.length > 0) {
          this.baseForm.zoneId = this.zoneList[0].zoneId
          this.changeZoneList()
        }
      }).catch(error => {
        _self.loading.zoneId = false
      })
    },
    // 获取专有网络
    getVpcList() {
      let _self = this
      _self.loading.vpcId = true
      request({
        url: '/cloud/pub/v1.0/vpc/getVpcList?dataCenterId=' + this.baseForm.cloudPlatformId + '&regionUuid=' + this.baseForm.regionId,
        method: 'get'
      }).then(data => {
        _self.loading.vpcId = false
        this.vpcList = data.data.pageData
        if (this.vpcList.length > 0) {
          this.baseForm.vpcId = this.vpcList[0].vpcId
          this.changeVpcList()
        }
      }).catch(error => {
        _self.loading.vpcId = false
      })
    },
    // 获取专有网络
    getSwitchList() {
      let _self = this
      _self.loading.switchId = true
      request({
        url: '/cloud/pub/v1.0/switch/getSwitchList',
        method: 'get',
        params: {
          dataCenterId: this.baseForm.cloudPlatformId,
          regionId: this.baseForm.regionId,
          zoneId: this.baseForm.zoneId,
          vpcId: this.baseForm.vpcId,
        }
      }).then(data => {
        _self.loading.switchId = false
        this.switchList = data.data.pageData
        if (this.switchList.length > 0) {
          this.baseForm.switchId = this.switchList[0].vSwitchId
        }
      }).catch(error => {
        _self.loading.switchId = false
      })
    },
    // 数据库版本
    getVersion() {
      let _self = this
      _self.loading.version = true
      request({
        url: '/cloud/pub/v1.0/mysql/versions/versionList',
        method: 'get',
        params: {
          dataCenterId: this.baseForm.cloudPlatformId,
          regionId: this.baseForm.regionId,
          zoneId: this.baseForm.zoneId
        }
      }).then(data => {
        _self.loading.version = false
        _self.versionList = data.data
        if (_self.versionList.length > 0) {
          _self.baseForm.version = this.versionList[0]
          _self.changeVersion()
        }
      }).catch(error => {
        _self.loading.version = false
      })
    },
    // 实例规格
    getInstanceTypeList() {
      let _self = this
      _self.loading.instanceType = true
      _self.baseForm.instanceType = ''
      // memorySize: this.baseForm.memorySize,
      // rdsMysqlDeviceType: 'UNIVERSALITY',
        request({
        url: '/cloud/pub/v1.0/mysql/instanceTypes/list',
        method: 'get',
        params: {
          dataCenterId: this.baseForm.cloudPlatformId,
          regionId: this.baseForm.regionId,
          zoneId: this.baseForm.zoneId,
          pageNumber: this.pagination.currentPage,
          pageSize: this.pagination.size,
          instanceChargeType: 'POSTPAID',
          typeName: 'BASIC',
          engineVersion: this.baseForm.version,
          cpu: this.baseForm.cpuCoreCount,
          diskType: this.diskForm.systemDiskList[0].type
        }
      }).then(data => {
        _self.loading.instanceType = false
        this.pagination.total = data.data.total
        this.instanceTypeList = data.data.pageData
      }).catch(error => {
        _self.loading.instanceType = false
      })
    },
    // 修改实例规格
    selectInstanceType(selection, row) {
      if (selection.length > 1) {
        let del_row = selection.shift()
        this.$refs.instanceTypeList.toggleRowSelection(del_row, false)
      }
      this.baseForm.instanceType = row.typeId
    },
    // 修改磁盘类型
    changeDiskType() {
      this.getInstanceTypeList()
    },
    selectInstanceTypeAll(selection) {
      this.baseForm.instanceType = ''
      this.$refs.instanceTypeList.clearSelection();
    },
    getInstanceTypeKey(row) {
      return row.instanceType
    },
    // 磁盘类型
    getDiskData() {
      let _self = this
      _self.loading.sysDiskType = true
      // 清空磁盘类型
      _self.sysDiskTypeList = []
      // 清空磁盘内容
      _self.diskForm.systemDiskList = []
      // 系统磁盘类型
      request({
        url: '/cloud/pub/v1.0/rds/mysql/disk_type/listDataDiskType',
        method: 'get',
        params: {
          dataCenterId: this.baseForm.cloudPlatformId,
          regionId: this.baseForm.regionId,
          zoneId: this.baseForm.zoneId,
          engineVersion: this.baseForm.version,
          instanceChargeType: 'POSTPAID',
          pubRdsMysqlArchType: 'BASIC'
        }
      }).then(data => {
        _self.loading.sysDiskType = false
        _self.sysDiskTypeList = data.data
        if (_self.sysDiskTypeList.length > 0) {
          _self.diskForm.systemDiskList = []
          _self.diskForm.systemDiskList.push({
            type: this.sysDiskTypeList[0].diskType,
            capacity: this.sysDiskTypeList[0].min,
            quantity: null,
            iops: '-',
            performance: '-',
            release: true
          })
          _self.getInstanceTypeList()
        }
      }).catch(error => {
        _self.loading.sysDiskType = false
      })
    },
    // 安全组动作
    handleSecurityGroupChange(val) {
      this.baseForm.securityGroups = val;
    },
    // 安全组
    getSecurityGroupList() {
      let _self = this
      request({
        url: '/cloud/pub/v1.0/security_group/listSecurityGroup',
        method: 'get',
        params: {
          dataCenterId: this.baseForm.cloudPlatformId,
          regionId: this.baseForm.regionId
        }
      }).then(data => {
        _self.securityGroupList = data.data
      }).catch(error => {
      })
    },
    // 实例调整分页
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.getInstanceTypeList()
    },
    // 数据盘添加一行
    createNetwork() {},
    createSwitch() {},
    cancel() {
      this.$router.push({name: 'pubVmList'})
    },
    // 创建实例
    createInstance() {
      const option = this.vpcList.find(i => i.vpcId === this.baseForm.vpcId)

      let createReq = {
        dataCenterId: this.baseForm.cloudPlatformId,
        dbInstanceClass: this.baseForm.instanceType,
        dbInstanceStorageType: this.diskForm.systemDiskList[0].type,
        dbInstanceStorage: this.diskForm.systemDiskList[0].capacity,
        engineVersion: this.baseForm.version,
        instanceChargeType: this.baseForm.instanceChargeType,
        payType: this.baseForm.instanceChargeType,
        securityIPList: option.cidrBlock,
        port: this.baseForm.port,
        regionId: this.baseForm.regionId,
        switchId: this.baseForm.switchId,
        vpcId: this.baseForm.vpcId,
        zoneId: this.baseForm.zoneId,
        instanceName: this.baseForm.instanceName,
      }

      request({
        url: '/cloud/pub/v1.0/rds/mysql/instance/create',
        method: 'post',
        data: createReq
      }).then(data => {
        this.$message({type: 'success', message: '任务提交成功!'})
        this.$router.push({name: 'pubMysqlList'})
      }).catch(error => {
        console.error(error)
      })
    },
    // 实例询价
    instancePrice() {
      if (!this.createInstanceDisabled) {
        // 包月包年的时长
        const durationOption = this.durationList.find(i => i.id === this.payForm.duration)
        let _self = this
        let req = {
          amount: 1,
          dataCenterId: this.baseForm.cloudPlatformId,
          regionId: this.baseForm.regionId,
          zoneId: this.baseForm.zoneId,
          instanceType: this.baseForm.instanceType,
          instanceChargeType: this.baseForm.instanceChargeType,
          systemDisk: {
            diskType: this.diskForm.systemDiskList[0].type,
            diskSize: this.diskForm.systemDiskList[0].capacity
          },
          period: this.baseForm.instanceChargeType == 'PREPAID' ? durationOption.period: 0,
          priceUnit: this.baseForm.instanceChargeType == 'PREPAID' ? durationOption.unit : 'Year',
        }
        request({
          url: '/cloud/pub/v1.0/inquiry_rice/inquiry',
          method: 'post',
          data: req
        }).then((data) => {
          _self.price.tradePrice = data.data.tradePrice
          _self.price.bandwidthPrice = data.data.bandwidthPrice
        })
      }
    },
  }
}
